package com.example.bzh.gamecat.util;

import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by lenovo on 2016/7/30.
 */
public class OkHttpUtil {
    private static OkHttpClient okHttpClient ;
    private Context context ;

    private OkHttpUtil(Context context){
        this.context = context ;
        if (okHttpClient==null){
            okHttpClient = new OkHttpClient();
        }
    }

    private Request getRequest(String url){
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(url).build();
        return  request ;
    }

    private Response getResponse(String url) throws IOException {
        Response response = okHttpClient.newCall(getRequest(url)).execute();
        return response;
    }

    private ResponseBody getResponseBody(String url) throws IOException {
        Log.i("TAG","ResponseBodyurl="+url);
        ResponseBody body = getResponse(url).body();
        return  body;
    }

    //同步请求
    public static String getRequestExe(String url,Context context) throws IOException {
         return  new OkHttpUtil(context).getResponseBody(url).string();
    }

    public static void getRequestEnq(String url,Context context, Callback callback){
        Request request = new OkHttpUtil(context).getRequest(url);
        okHttpClient.newCall(request).enqueue(callback);
    }
}
